package org.xhnews.bo;

import java.util.Date;
import java.util.Vector;

import org.xhnews.constant.Constant;
import org.xhnews.database.DatabaseManager;
import org.xhnews.download.DownloadManager;
import org.xhnews.log.RaspberryLogger;
import org.xhnews.preferences.Preferences;
import org.xhnews.to.NewsChannel;
import org.xhnews.to.NewsItem;
import org.xhnews.utils.DeviceUtil;
import org.xhnews.utils.NetworkUtil;
import org.xhnews.utils.StringUtil;

public class NewsBo {
	/*
	 * 获得所有处于激活状态的新闻频道列表
	 */
	public static Vector getAllEnableChannels() {
		return DatabaseManager.getAllEnableChannels();
	}
	/*
	 * 根据新闻频道中的文件名称获得该频道的所有新闻条目
	 */
	public static Vector getNewsByChannel(String channelFileName) {
		return DatabaseManager.getNewsByChannel(channelFileName);
	}
	/*
	 * 根据新闻条目ID获得该新闻的正文
	 */
	public static String getNewsItemContent(String id){
		return DatabaseManager.getNewsItemContent(id);
	}
	/*
	 * 获得最新的新闻条目
	 */
	public static Vector getLatestNews() {
		return DatabaseManager.getLatestNews();
	}
	/*
	 * 获得收藏的新闻条目
	 */
	public static Vector getFavorNews() {
		return DatabaseManager.getFavorNews();
	}
	/*
	 * 设置新闻条目为已读状态
	 */
	public static boolean setItemRead(String itemId) {
		return DatabaseManager.setItemRead(itemId, true);
	}
	/*
	 * 设置新闻条目为收藏状态
	 */
	public static boolean setItemFavor( String itemId) {
		return DatabaseManager.setItemFavor(itemId, true);
	}
	/*
	 * 设置新闻条目为收藏状态
	 */
	public static boolean clearItemFavor( String itemId) {
		return DatabaseManager.setItemFavor(itemId, false);
	}
	/*
	 * 获得频道在频道列表中的位置
	 * 注：是updateAllEnableChannelNews方法的辅助方法 
	 */
	public static int getIndexOfContainer(NewsChannel channel, Vector channels) {
		int length = channels.size();
		for (int i = 0; i < length; i++)
			if (channel.getFileName().equals(
					((NewsChannel) channels.elementAt(i)).getFileName()))
				return i;
		return -1;
	}
	/*
	 * 更新所有处于激活状态的频道新闻
	 * 1、更新激活的新闻
	 * 2、服务器端没有新新闻的频道不更新
	 * 3、根据用户选择的更新方式更新
	 * 3、同步频道列表
	 * 4、刷新新闻更新的最后时间news_last_update_time参数值
	 */
	public static void updateAllEnableChannelNews() {
		Vector localChannels = DatabaseManager.getAllEnableChannels();
		String url = Preferences.server_address + Constant.URL_CHANNELLIST
				+ "imei=" + DeviceUtil.getPhoneIMEI();
		Vector serverChannels = DownloadManager.downloadNewsChannelList(url);
		if (localChannels != null) {
			int length = localChannels.size();
			for (int i = 0; i < length; i++) {
				NewsChannel newschannel = (NewsChannel) localChannels
						.elementAt(i);
				int pos = getIndexOfContainer(newschannel, serverChannels);
				if (pos != -1) {
					int maxID_local = Integer.parseInt(newschannel
							.getMaxNewsID());
					int maxID_server = Integer
							.parseInt(((NewsChannel) serverChannels
									.elementAt(pos)).getMaxNewsID());
					if (maxID_server <= maxID_local) {
						serverChannels.removeElementAt(pos);
					}
				}
			}
		}
		for (int j = 0; j < serverChannels.size(); j++) {
			DatabaseManager.insertNewsChannel((NewsChannel) serverChannels
					.elementAt(j));
			downloadAndSaveChannelsNeeded(Preferences.news_download_type,
					(NewsChannel) serverChannels.elementAt(j));
		}
	}

	private static  void downloadAndSaveChannelsNeeded(int downloadtype,NewsChannel newschannel){
		Vector items = DownloadManager.downloadNewsItems(
				Preferences.server_address+Constant.URL_NEWSLIST, newschannel);
		DatabaseManager.insertNewsItems(items, newschannel.getLink(),
				Preferences.news_max_count_per_channel,
				Constant.PATH_DATA);
		String content="";
		switch (Preferences.news_download_type) {
		case 1:// 仅标题
			break;
		case 2:// 全文下载(图片视频)
			for (int j = 0; j < items.size(); j++) {
				String html=StringUtil.is2String(DownloadManager.send(Preferences.server_address+Constant.URL_XML+((NewsItem)items.elementAt(j)).getFileName()));
				if (html != null) {
					content = StringUtil.replaceAll("src=\""," width=\"240px\" "+ "src=\"file:///SDCard/"+Constant.PATH_DATA,html);
					content = StringUtil.replaceAll("href=\""," width=\"240px\" "+ "href=\"file:///SDCard/"+Constant.PATH_DATA,content);
					RaspberryLogger.getInstance().info(content);
					DatabaseManager.setNewsItemContent(((NewsItem)items.elementAt(j)).getID(),
							content);
					DownloadManager.downloadAndSaveAttachment(
							Preferences.server_address+Constant.URL_XML, Constant.PATH_DATA,
							(NewsItem) items.elementAt(j));
				}
				
			}
			break;
		case 3:// 仅用WiFi网络下载全文
			if (NetworkUtil.isWifiAvailable()) {
				for (int j = 0; j < items.size(); j++) {					
					String html=StringUtil.is2String(DownloadManager.send(Preferences.server_address+Constant.URL_XML+((NewsItem)items.elementAt(j)).getFileName()));
					if (html != null &&html.indexOf("failed")!=-1) {
						content = StringUtil.replaceAll("src=\""," width=\"240px\" "+ "src=\"file:///SDCard/"+Constant.PATH_DATA,html);
						content = StringUtil.replaceAll("href=\"", "href=\"file:///SDCard/"+Constant.PATH_DATA,content);
					
					DatabaseManager.setNewsItemContent(((NewsItem)items.elementAt(j)).getID(),
							content);
					DownloadManager.downloadAndSaveAttachment(
							Preferences.server_address+Constant.URL_XML, Constant.PATH_DATA,
							(NewsItem) items.elementAt(j));
					}
				}
			}
			break;
		}
		Preferences.news_last_update_time = StringUtil
		.date2String(new Date());
	}
	/*
	 * 更新指定的频道新闻
	 * 1、服务器端没有新新闻的频道不更新
	 * 2、根据用户选择的更新方式更新
	 * 3、刷新新闻更新的最后时间news_last_update_time参数值
	 */
	public static void updateNewsByChannel(NewsChannel newschannel) {
		boolean success = false;
		Vector serverChannels = DownloadManager
				.downloadNewsChannelList(Preferences.server_address+Constant.URL_CHANNELLIST);
		int pos = getIndexOfContainer(newschannel, serverChannels);
		if (pos != -1) {
			int maxID_local = Integer.parseInt(newschannel.getMaxNewsID());
			int maxID_server = Integer.parseInt(((NewsChannel) serverChannels
					.elementAt(pos)).getMaxNewsID());
			if (maxID_server > maxID_local) {
				Vector items = DownloadManager.downloadNewsItems(
						Preferences.server_address+Constant.URL_NEWSLIST, newschannel);
				DatabaseManager.insertNewsItems(items, newschannel.getID(),
						Preferences.news_max_count_per_channel,
						Constant.PATH_DATA);
				switch (Preferences.news_download_type) {
				case 1:// 仅标题
					break;
				case 2:// 全文下载(图片视频)
					for (int j = 0; j < items.size(); j++) {
						DownloadManager.downloadAndSaveAttachment(
								Preferences.server_address+Constant.URL_XML, Constant.PATH_DATA,
								(NewsItem) items.elementAt(j));
					}
					break;
				case 3:// 仅用WiFi网络下载全文
					if (NetworkUtil.isWifiAvailable()) {
						for (int j = 0; j < items.size(); j++) {
							DownloadManager.downloadAndSaveAttachment(
									Preferences.server_address+Constant.URL_XML, Constant.PATH_DATA,
									(NewsItem) items.elementAt(j));
						}
					}
					break;
				}
				DatabaseManager.setChannelMaxNewsID(newschannel.getFileName(),
						"" + maxID_server);
				success = true;
			}
		}
		if (success)
			Preferences.news_last_update_time = StringUtil
					.date2String(new Date());
	}

	public static void updateVideoItems() {
		Vector items = DownloadManager
				.downloadVideoItems(Preferences.server_address
						+ Constant.URL_ONLINE_VIDEO + "imei="
						+ DeviceUtil.getPhoneIMEI());
		DatabaseManager.insertNewsItems(items, "OnlineVideo",
				Preferences.news_max_count_per_channel, Constant.PATH_DATA);
		for (int j = 0; j < items.size(); j++) {
			DownloadManager.downloadAndSavePictures(Preferences.server_address
					+ Constant.URL_XML, Constant.PATH_DATA, (NewsItem) items
					.elementAt(j));
		}
	}
	public static Vector getOnlineVideoItems(){
		return DatabaseManager.getVideoItems("OnlineVideo");
	}
	/*
	 * 获得所有新闻频道
	 */
	public static Vector getAllNewsChannels() {
		return DatabaseManager.getAllNewsChannels();
	}
	/*
	 * 根据新闻频道的文件名称删除新闻频道
	 * 注：除被收藏的新闻外，被删除频道的所有新闻都被删除
	 */
	public static void delChannel(String channelFileName) {
		DatabaseManager.delChannel(channelFileName);
		DatabaseManager.delNoChannelNews();
	}
	/*
	 * 插入新的新闻频道
	 */
	public static void insertNewsChannel(NewsChannel ch){
		DatabaseManager.insertNewsChannel(ch);
	}
	public static void setChannelEnable(String chName, boolean b){
		DatabaseManager.setChannelEnable(chName, b);
	}
	
	
}
